// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-15

package upload

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"mime/multipart"
	"server/app/lib"
)

// Logic
// 上传图片.
type Logic struct {
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		response: &Response{},
	}
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, i iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	// 1. 上传过程.
	if err = o.RunUpload(ctx, i); err != nil {
		return res.WithError(err)
	}
	// 2. 上传结果.
	return res.With(o.response)
}

// RunUpload
// 上传文件.
func (o *Logic) RunUpload(ctx context.Context, i iris.Context) (err error) {
	var header *multipart.FileHeader
	if _, header, err = i.FormFile("image"); err == nil {
		o.response.Image, err = lib.Uploader.Upload(ctx, header)
	}
	return err
}
